from django.db import models
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError


class Department(models.Model):
    """学部模型"""
    DEPARTMENT_CHOICES = [
        ('engineering', '工学部'),
        ('science', '理学部'),
        ('humanities', '文学部'),
        ('economics', '经济学部'),
        ('management', '管理学部'),
    ]
    
    name = models.CharField(
        max_length=20,
        choices=DEPARTMENT_CHOICES,
        unique=True,
        verbose_name='学部名称'
    )
    description = models.TextField(
        blank=True,
        verbose_name='学部描述'
    )
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    
    class Meta:
        verbose_name = '学部'
        verbose_name_plural = '学部'
        ordering = ['name']
        
    def __str__(self):
        return self.get_name_display()


class College(models.Model):
    """二级学院模型"""
    name = models.CharField(
        max_length=100, 
        unique=True,
        verbose_name='学院名称'
    )
    code = models.CharField(
        max_length=20,
        unique=True,
        verbose_name='学院代码',
        help_text='学院的唯一标识代码'
    )
    department = models.ForeignKey(
        Department,
        on_delete=models.CASCADE,
        null=True,
        blank=True,
        verbose_name='所属学部',
        help_text='学院所属的学部'
    )
    description = models.TextField(
        blank=True,
        verbose_name='学院描述',
        help_text='学院的详细描述信息'
    )
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    
    class Meta:
        verbose_name = '二级学院'
        verbose_name_plural = '二级学院'
        ordering = ['name']
        
    def __str__(self):
        return self.name
    
    @property
    def users_count(self):
        """获取关联用户数量"""
        return self.users.count()
    
    @property
    def subprojects_count(self):
        """获取关联子项目数量"""
        return self.subprojects.count()
    
    def get_users(self):
        """获取关联的用户列表"""
        return self.users.all()
    
    def get_subprojects(self):
        """获取关联的子项目列表"""
        return self.subprojects.all()


class UserProfile(models.Model):
    """用户扩展信息模型"""
    ROLE_CHOICES = [
        ('admin', '教务管理员'),
        ('college', '二级学院使用者'),
    ]
    
    user = models.OneToOneField(
        User, 
        on_delete=models.CASCADE,
        verbose_name='用户'
    )
    role = models.CharField(
        max_length=20, 
        choices=ROLE_CHOICES,
        verbose_name='角色'
    )
    college = models.ForeignKey(
        College,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name='users',
        verbose_name='所属学院',
        help_text='仅二级学院使用者需要设置'
    )
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    
    class Meta:
        verbose_name = '用户信息'
        verbose_name_plural = '用户信息'
        
    def __str__(self):
        return f"{self.user.username} - {self.get_role_display()}"
    
    def clean(self):
        """数据验证"""
        if self.role == 'college' and not self.college:
            raise ValidationError('二级学院使用者必须设置所属学院')
    
    @property
    def is_admin(self):
        """是否为管理员"""
        return self.role == 'admin'
    
    @property
    def is_college_user(self):
        """是否为二级学院使用者"""
        return self.role == 'college'
    
    @property
    def college_name(self):
        """获取学院名称（兼容性属性）"""
        return self.college.name if self.college else None